package controllers;

import play.mvc.*;
import static play.data.Form.*;

import java.util.*;

import models.*;

import views.html.*;

/**
 * Manage projects related operations.
 */
@Security.Authenticated(Secured.class)
public class Projects extends Controller {
		
    public static Result index() {
    	Account user = Account.findByName(request().username());
    	boolean isAdmin = AuthorHelper.isAdmin(user);
    	if (isAdmin) {
    		MenuWrapper mwroot = buildSuperUserMenus();
        	return ok(home.render(user, isAdmin, mwroot));
    	} else {
    		MenuWrapper mwroot = buildMenuWrapper(user);
        	return ok(home.render(user, isAdmin, mwroot));
    	}	
    }
    
    public static MenuWrapper buildMenuWrapper(Account user) {
    	List<Account_role> ars = Account_role.find.where().eq("account.id", user.getId()).findList();
    	List<Role_menu_permission> rmps = new ArrayList<Role_menu_permission>();
    	for (Account_role ar : ars) {
    		List<Role_menu_permission> rmps2 = Role_menu_permission.find.where().eq("role.id", ar.getRole().getId()).findList();
    		for(Role_menu_permission rmp: rmps2) {
    			rmp.setMenu(Menu.findById(rmp.getMenu().getId()));
    		}
    		rmps.addAll(rmps2);
    	}
    	return buildMenuWrapper(rmps); 
	}
    
    public static MenuWrapper buildSuperUserMenus() {
    	List<Role_menu_permission> rmps = new ArrayList<Role_menu_permission>();
    	for(Menu m : Menu.find.all()) {
    		Role_menu_permission rmp = new Role_menu_permission();
    		rmp.setMenu(m);
    		rmps.add(rmp);
    	}
    	return buildMenuWrapper(rmps);
    }
    
    public static MenuWrapper buildMenuWrapper(List<Role_menu_permission> rmps) {
    	Menu root = new Menu();
    	root.setId(0);
    	root.setName("");
    	root.setPid(-1);
    	
    	MenuWrapper rootmw = new MenuWrapper(root);
    	for(Role_menu_permission rmp: rmps) {
    		MenuWrapper.insertMenu(rootmw, new MenuWrapper(rmp.getMenu()));
    	}
    	
    	return rootmw;
    }
    
}

